package com.youlu.campus.service.qa;

import com.youlu.campus.entity.english.UserCompetitionQaAnswer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class UserCompetitionQaAnswerService {

    @Autowired
    private MongoTemplate mongoTemplate;


    public UserCompetitionQaAnswer findByUserIdAndQaInfoIdAndActivityId(String userId,String qaInfoId, String activityId){
        //获取用户提交答题记录
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("qaInfoId").is(qaInfoId));
        query.addCriteria(Criteria.where("activityGroupId").is(activityId));
       return this.mongoTemplate.findOne(query, UserCompetitionQaAnswer.class);

    }

    @Async
    public void remove(String userId,String qaInfoId, String activityId){
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("qaInfoId").is(qaInfoId));
        query.addCriteria(Criteria.where("activityGroupId").is(activityId));
        this.mongoTemplate.remove(query,UserCompetitionQaAnswer.class);
        String deleteTag = "-delete";
        Update update = new Update();
        update.set("userId",userId+deleteTag);
        update.set("qaInfoId",qaInfoId+deleteTag);
        update.set("activityGroupId",activityId+deleteTag);
       this.mongoTemplate.updateMulti(query,update,UserCompetitionQaAnswer.class);

        log.info("【重置练习题】userId - > {} qaInfoId-> {} activityId - > {}", userId,qaInfoId,activityId);
    }

    @Async
    public void saveOrUpdate(UserCompetitionQaAnswer userCompetitionQaAnswer){
      this.mongoTemplate.save(userCompetitionQaAnswer);
    }


}
